from pms.common.views import PostFormula
from user.utils.login import gen_token_factor, LoginError, get_user_by_uid, get_uid


class API(PostFormula):

    require_permissions = [2]

    def handle(self, req):
        try:
            account = req['account']
            password = req['password']
            cid = req['cid']
            token_factor = gen_token_factor(account, password, cid)
            self.check_permissions(get_user_by_uid(get_uid(account, password)))
            return self.success_respond({
                'token_factor': token_factor
            })
        except LoginError as le:
            if le.t == 'WRONG_PASSWORD':
                return self.failed_respond('WRONG_PASSWORD', '密码错误')
            elif le.t == 'ACCOUNT_NOT_EXIST':
                return self.failed_respond('ACCOUNT_NOT_EXIST', '账户不存在')
